import { useConfigStore } from '@/stores/modules/configStore';
import loading from '@/utils/loading';
import { useUser } from '@/utils/useUser';

/**
 * @param 支付宝相关request封装
 */

const configStore = useConfigStore();
const { apiConfig, constants } = configStore;

const request = (obj) => {
  const config = {
    ...apiConfig,
    ...obj
  };
  config.url = apiConfig.url + obj.url;
  if (obj.headers)
    config.headers = {
      ...apiConfig.headers,
      ...obj.headers
    };
  console.log(obj, config);

  //是否拦截
  console.log(useRequestInterception(config));
  if (useRequestInterception(config)) return;
  return new Promise((resolve, reject) => {
    const closeLoding = loading.startLoading(obj.url);
    uni
      .request(config)
      .then((res) => {
        console.log(obj.url, res, '------a----');
        const data = useResponseInterception(res);
        if (data.errorLogin) {
          reject(data);
          return;
        }
        resolve(data);
      })
      .catch((err) => {
        closeLoding();
        reject(err.data);
        if (err.status == 460) {
          useUser.isInvalidLogin();
        }
        if (err.errorCode == 19) {
          uni.showToast({
            content: err.errorMessage
          });
        }
      })
      .finally((e) => {
        closeLoding();
      });
  });
};

//请求拦截
const useRequestInterception = (config) => {
  config.headers['Authorized-Token'] = uni.getStorageSync('TOKEN') || '';

  return false;
};
//响应拦截
const useResponseInterception = (res) => {
  console.log(res);
  if (res.data.code == '509') {
    return {
      msg: '请登录!',
      code: '509',
      errorLogin: true
    };
  }
  if (res.data.code == '502') {
    useUser.isInvalidLogin();
    return {
      msg: '登录超时',
      errorLogin: true
    };
  }

  return res.data;
};

export default request;
